﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Xml;
using DaInterFace;
using DaInterFace.Mobile;

namespace DaFunction.Mobile
{
    [ServiceContract()]
    public interface IMobileApi
    {
        [OperationContract]
        string GetAccounts();

        [OperationContract]
        string GetSeed();

        [OperationContract]
        string Login(string key, string parameter);

        [OperationContract]
        string Code(string parameter);


        [OperationContract]
        string GetConfig();

    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
    public class MobileApi : IMobileApi
    {
        private const String PublicKey = "V63JxeExiKi0ZziL";

        public static IMobile DaMobile;

        private static Dictionary<string, MobileUser> UserDictionary = new Dictionary<string, MobileUser>();
        private static Dictionary<string, PublicKeyTemp> PublicKeys = new Dictionary<string, PublicKeyTemp>();
        private static Dictionary<string, MobileUser> BlackList = new Dictionary<string, MobileUser>();

        public string GetSeed()
        {
            RSAInfo rsa = new RSAInfo();
            String seedKey = "";
            String key = "";

            seedKey = Guid.NewGuid().ToString("n").Substring(3, 16);
            key = Guid.NewGuid().ToString("n");
            PublicKeyTemp temp = new PublicKeyTemp();

            rsa.SeedKey = seedKey;
            rsa.Key = key;

            temp.SeedKey = seedKey;
            temp.VistTime = DateTime.Now;

            PublicKeys.Add(key, temp);

            //foreach (string name in PublicKeys.Keys)
            //{
            //    if (DateTime.Now - PublicKeys[name].VistTime > TimeSpan.FromSeconds(3))
            //    {
            //        PublicKeys.Remove(name);
            //    }
            //}
            return DaMobile.Json.ClassToJson(rsa);
        }
        //获得配置文件信息
        public string GetConfig()
        {
            //string strAppPath = System.Environment.CurrentDirectory;
            string strAppPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            if (!File.Exists(strAppPath + @"\config.txt"))
            {
                return "";
            }
            string str = File.ReadAllText(strAppPath + @"\config.txt", Encoding.Default);
            return str;
            /*string strAppPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            if (!Directory.Exists(strAppPath)) 
            {
                Directory.CreateDirectory(strAppPath);
            }
            if (!File.Exists(strAppPath + @"\config.txt"))
            {
                //File.Create(strAppPath + @"\config.txt");
                FileStream fs = new FileStream(strAppPath + @"\config.txt", FileMode.Create);
                StreamWriter sw = new StreamWriter(fs);
                //获得公司服务器config
                DataSet ds = new DataSet("ApkVersion");
                ds = GetConnection(GetPublicIP());
                String ConfigText = ds.Tables["MyConfig"].Rows[0]["ConfigText"].ToString();
                //开始写入
                sw.Write(ConfigText);
                //清空缓冲区
                sw.Flush();
                //关闭流
                sw.Close();
                fs.Close();
            }
            FileStream aFile = new FileStream(strAppPath + @"\config.txt", FileMode.Open);
            StreamReader sr = new StreamReader(aFile);
            //string str = File.ReadAllText(strAppPath + @"\config.txt", System.Text.Encoding.Default);
            string str = sr.ReadLine();
            return str;*/

        }
        public string GetAccounts()
        {
            Dictionary<String,SetOfBook> books = DaMobile.Data.GetAccounts();
            return DaMobile.Json.ClassToJson(books);
        }

        private int CheckUser(MobileClient mc)
        {
            if (UserDictionary.ContainsKey(mc.UserName))
            {
                if (UserDictionary[mc.UserName].IMEI == mc.IMEI && UserDictionary[mc.UserName].Key == mc.Key)
                {
                    UserDictionary[mc.UserName].VisitTime = DateTime.Now;
                    return 0;
                }
                else
                {
                    return 1;
                }
            }
            else
            {
                return 2;
            }
        }

        private ClientUser ConvertUserClass(MobileUser mu)
        {
            ClientUser cu = new ClientUser();
            cu.AccountID = mu.AccountID;
            cu.UserName = mu.UserName;
            cu.LoginTime = mu.LoginTime;
            cu.VisitTime = mu.VisitTime;

            return cu;
        }

        public string Login(string key,string parameter)
        {
            LoginResult cr = new LoginResult();
            MobileUser mu = new MobileUser();
            String aesParam = ""; ;

            //获取消息发送的远程终结点IP和端口
            RemoteEndpointMessageProperty endpoint = OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
            
            try
            {
                if (!PublicKeys.ContainsKey(key))
                {
                    cr.Enable = false;
                    cr.Message = "加密错误";
                }
                else
                {
                    mu.SeedKey = PublicKeys[key].SeedKey;
                    aesParam = AES.Decrypt(parameter, mu.SeedKey);

                    LoginParameters p = (LoginParameters)DaMobile.Json.JsonToClass(aesParam, typeof(LoginParameters));

                    SqlParameter[] sps = new SqlParameter[1];
                    sps[0] = new SqlParameter("@UserName", SqlDbType.NVarChar, 50);
                    sps[0].Value = p.UserName;

                    String sql = "SELECT FText Pswd,FCheckBox1 IMEI FROM KEW_SalesGuests WHERE FCheckBox=1 AND FBillNo=@UserName\r\nSELECT FText2 IMEI FROM KEW_SalesGuestsIMEI WHERE FID =(SELECT FID FROM KEW_SalesGuests WHERE FCheckBox=1 AND FBillNo=@UserName)";
                    Recordset rs = DaMobile.Data.ExeProcedure(p.AccountID, sql, sps);

                    if (rs.Enable)
                    {
                        if (rs.Data.Tables[0].Rows.Count != 1)
                        {
                            cr.Enable = false;
                            cr.Message = "用户名错误";
                        }
                        else if (rs.Data.Tables[0].Rows[0]["Pswd"].ToString() != p.PassWord)
                        {
                            cr.Enable = false;
                            cr.Message = "密码错误";
                        }
                        else
                        {
                            Boolean isIMEI = false;
                            if (Common.CBool(rs.Data.Tables[0].Rows[0]["IMEI"].ToString()))
                            {
                                foreach (DataRow row in rs.Data.Tables[1].Rows)
                                {
                                    if (row["IMEI"].ToString() == p.IMEI)
                                    {
                                        isIMEI = true;
                                    }
                                }
                            }
                            else
                            {
                                isIMEI = true;
                            }
                            if (isIMEI)
                            {
                                UserDictionary.Remove(p.UserName);

                                mu.Key = key;
                                mu.IMEI = p.IMEI;
                                mu.AccountID = p.AccountID;
                                mu.UserName = p.UserName;
                                mu.LoginTime = DateTime.Now;
                                mu.VisitTime = DateTime.Now;
                                UserDictionary.Add(mu.UserName, mu);

                                cr.Enable = true;
                                cr.Key = mu.Key;
                                cr.VistSpan = Common.CInt(DaMobile.Config.Get("Vist"));
                                //DaMobile.Message(MessageType.Note, String.Format("用户[{0}]登录成功，IMEI：{1},IP:{2}", p.UserName, p.IMEI, endpoint.Address));
                                DaMobile.Message(MessageType.Note, String.Format("用户[{0}]登录成功，IMEI：{1}", p.UserName, p.IMEI));
                            }
                            else
                            {
                                cr.Enable = false;
                                cr.Message = "此设备不允许登录！";
                                DaMobile.Message(MessageType.Warning, String.Format("用户[{0}]登录的设备不在允许的范围内，IMEI：{1}", p.UserName, p.IMEI));
                            }
                        }
                    }
                    else
                    {
                        cr.Enable = false;
                        cr.Message = rs.Message;
                    }
                }

            }
            catch (Exception ex)
            {
                cr.Enable = false;
                cr.Message = ex.Message;
            }

            return DaMobile.Json.ClassToJson(cr);
        }
        public string Code(string parameter)
        {
            CodeResult cr = new CodeResult();
            
            string str = AES.Decrypt(parameter, PublicKey);
            MobileParameter mp = (MobileParameter)DaMobile.Json.JsonToClass(str, typeof(MobileParameter));

            String crstring = string.Empty;
            String[] splitCode = mp.CodeName.Split('.');

            if (splitCode.Length != 2)
            {
                cr.Enable = false;
                cr.Message = "错误的功能代码！";

                return DaMobile.Json.ClassToJson(cr);
            }
            String file = splitCode[0];
            String code = splitCode[1];
            
            int crst = CheckUser(mp.Client);

            switch (crst)
            {
                case 0:
                    try
                    {
                        MobileUser serveruser = UserDictionary[mp.Client.UserName];
                        ClientUser user = ConvertUserClass(serveruser);
                        Assembly ass = Assembly.Load(file);  //加载dll文件
                        Type tp = ass.GetType(file + "." + code);  //获取类名，必须 命名空间+类名
                        IMobileChild temp = (IMobileChild)Activator.CreateInstance(tp);  //建立实例
                        cr.JsonObj = temp.Code(DaMobile, user, serveruser.Decrypt(mp.Parameters));
                        cr.Enable = true;
                        cr.Result = 0;

                    }
                    catch (Exception ex)
                    {
                        cr.Enable = false;
                        cr.Result = 4;
                        cr.Message = "Code代码错误，请联系管理人员：" + mp.CodeName + ex.Message;
                        DaMobile.Message(MessageType.Error, mp.CodeName + ":" + ex.Message);
                    }
                    break;
                case 1:
                    cr.Enable = false;
                    cr.Result = 1;
                    cr.Message = "无效的登录信息，请重新登录。";
                    break;
                case 2:
                    cr.Enable = false;
                    cr.Result = 2;
                    cr.Message = "请先登录。";
                    break;
            }

            return crstring = DaMobile.Json.ClassToJson(cr);
        }
    }
}
